// pages/name/name.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    radioValue: 'GG', // 初始时没有选中的值
    nameDescription: "",
    isRecharge:false,
    buttonTexts: [
      {
        type: 'primary',
        text: '取消',
        value: 0
      },
      { 
        type: 'default',
        text: '9.9元/3次',
        value: 1,
    }],
    items: [
      { name: '食物', selected: false },
      { name: '清新', selected: false },
      { name: '洋气', selected: false },
      { name: '英文', selected: false },
      { name: '动物', selected: false },
      { name: '日期', selected: false },
      { name: '新潮', selected: false },
      { name: '可爱', selected: false },
      { name: '水果', selected: false },
      { name: '植物', selected: false }
    ]
  },
  toggleSelect: function (e) {
    const index = e.currentTarget.dataset.index;
    const selected = !this.data.items[index].selected;

    // 更新数据
    this.setData({
      ['items[' + index + '].selected']: selected
    });
  },
  radioChange(e) {
    const value = e.currentTarget.dataset.value;
    console.log("value:" + value);
    this.setData({
      radioValue: value,
    });
  },

  inputDescriptionChange(e) {
    this.setData({
      nameDescription: e.detail.value
    })
  },

  radioCheckChange(e) {
    let index = e.currentTarget.dataset.index;
    this.data.items[index].selected = !(this.data.items[index].selected);
    console.log('点击的元素的 index:', this.data.items[index].selected);
    var dataList = this.data.items;
    this.setData({
      items: dataList,
    });
  },

  requestDataFromServer: function () {
  //   var Bmob = require('../../dist/Bmob-2.5.2.min')
  //   var openid = wx.getStorageSync('openid');
  //   const query = Bmob.Query("Count");
  //   query.equalTo("openid", "==", openid);
  //   query.find().then(res => {
  //     if (Array.isArray(res)) {
  //       var count = Bmob.Query('Count');
  //       if(res.length == 0){
  //         count.set("openid",openid);
  //         count.set("count", 2);
  //         count.save().then(res => {
  //           this.toAIName() 
  //         })
  //       }else{
  //         var item = res[0]
  //         var countNumber = item.count;
  //         if(countNumber==0){
  //           this.setData({
  //             isRecharge: true,
  //           });
  //           return;
  //         }
  //         countNumber = countNumber - 1;

  //         count.set('id', item.objectId) //需要修改的objectId
  //         count.set("count", countNumber)
  //         count.save().then(res => {
  //           console.log(res)
  //           }).catch(err => {
  //           console.log(err)
  //           })
  //         //开始ai 生成名字
  //         this.toAIName() 
  //       } 
  //     }
  // });    
   //开始ai 生成名字
    this.toAIName() 
  },


  toAIName: function () {

    let aiName = '生成5个宝宝乳名，乳名要求：' +  this.data.nameDescription;
    if (this.data.radioValue == "GG") {
      aiName = "生成5个男性宝宝的乳名"
      console.log("GG")
    } else {
      aiName = "生成5个女性宝宝的乳名"
      console.log("MM")
    }

    aiName = aiName + "   乳名要求: "+this.data.nameDescription
    
    var style = "";
    var selected = false;
    for (var i = 0; i < this.data.items.length; i++) {
      if (this.data.items[i].selected) {
        selected = true;
        style += this.data.items[i].name+","
      }
    }
    if(selected){
      style = "   乳名风格: "+style+" ";
    }
    aiName = aiName + style;

    aiName = aiName + "返回结果必须是JSON数组,不需要带上```json,其中name代表名字全称,meaning代表名字含义,pinyin代表名字的拼音,返回的JSON数组只需要包括,name,meaning,pinyin三个变量,"

    console.log("ainame = " + aiName)
    
    var Bmob = require('../../dist/Bmob-2.5.2.min')
    let chatAi = Bmob.ChatAI()
    let data = {
      "messages": [{
        "content": aiName,
        "role": "user"
      }],
      "session": "b1"
    }
    console.log("JSON = " + JSON.stringify(data))
    setTimeout(function () {
      chatAi.send(JSON.stringify(data))
   }, 2000);

    let msg = ""

    chatAi.onClose((c) => {
      console.log("连接被关闭");
      //重新连接
      chatAi.connect()
    })

    wx.showLoading({
      title: 'ai生成中...', // 加载提示框的标题
      mask: true // 是否显示透明蒙层，防止触摸穿透，默认为false
    });

    chatAi.onMessage((res) => {
      if (res == "done" && msg.length > 0) {
        wx.hideLoading(); // 关闭加载框
        msg = msg.replace("param1:","");
        msg = msg.replace("```json", "");
        msg = msg.replace("```", "");
        console.log('../result/result?result='+msg);
        wx.navigateTo({
          url: '../result/result?result='+msg
        })
      } else if(res!="done"){
        msg = msg + res   
      }
    })
    chatAi.onError((c) => {
      console.log("连接错误");
      wx.hideLoading(); // 关闭加载框
      wx.showToast({
        title: '服务器异常',
        icon: 'error',
      })
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  startPay(e) {
    const { value } = e.detail.item;
    if (value === 0) {
      this.setData({
        isRecharge: false
      });
    } else if (value === 1) {
      this.setData({
        isRecharge: false
      });
    }
  },

  onShareAppMessage: function (res) {
    return {
      title: 'AI起名专家',
      path: '/pages/main/main.wxml'
    }
  }
})